package com.github.tyc.listener;

import com.github.tyc.entity.SysJob;
import com.github.tyc.service.JobService;
import com.github.tyc.util.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;

import java.util.List;

/**
 * 监听容器刷新完成后初始化定时任务
 *
 * @author tyc
 * @version 1.0
 * @date 2023-04-21 16:22:01
 */
@Slf4j
public class ScheduleJobBootstrapListener extends OneTimeExecutionApplicationContextEventListener implements Ordered {

    @Override
    public void onApplicationContextEvent(ApplicationContextEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            onContextRefreshedEvent((ContextRefreshedEvent) event);
        } else if (event instanceof ContextClosedEvent) {
            onContextClosedEvent((ContextClosedEvent) event);
        }
    }

    private void onContextRefreshedEvent(ContextRefreshedEvent event){
        log.info("start init schedule job");
        JobService jobService = event.getApplicationContext().getBean(JobService.class);
        Scheduler scheduler = event.getApplicationContext().getBean(Scheduler.class);
        // 初始化定时器
        List<SysJob> scheduleJobList = jobService.list();
        for(SysJob scheduleJob : scheduleJobList){
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
        log.info("init schedule job success.");
    }



    private void onContextClosedEvent(ContextClosedEvent event){
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
